!function (global, $) {
    const S7BuyClient = function (config) {
        this.loading = false;
        this.oldScroolIndex = 0;
        this.isLogin = (typeof config === typeof undefined
            ||typeof config.isLogin ===  typeof undefined)?false:config.isLogin;
        this.common = {
            defaultShareText:'{%title%}{%%}'
        };
        this.listView = null;
        this.keepTime = 60;
        this.categoryParams = {};
        Number.prototype.formats = function () {
          let s = this.toString();
          let rs = s.indexOf('.');
            if (rs < 0) {
                rs = s.length;
                s += '.';
            }
            while (s.length <= rs + 2) {
                s += '0';
            }
            return s;
        };
        Date.prototype.format = function(fmt) {
            var o = {
                "M+" : this.getMonth()+1,                 //月份
                "d+" : this.getDate(),                    //日
                "h+" : this.getHours(),                   //小时
                "m+" : this.getMinutes(),                 //分
                "s+" : this.getSeconds(),                 //秒
                "q+" : Math.floor((this.getMonth()+3)/3), //季度
                "S"  : this.getMilliseconds()             //毫秒
            };
            if(/(y+)/.test(fmt)) {
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            }
            for(var k in o) {
                if(new RegExp("("+ k +")").test(fmt)){
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
                }
            }
            return fmt;
        };
        this.handleScrollEvent = this.handleScrollEvent.bind(this)
    };
    S7BuyClient.prototype = {
        init: function () {
            $(global.document).on('click','.goods-list-item',function () {
                const id = $(this).attr('id');
                global.location.href = '/goods?numId=' + id;
            });
            $(global.document).on('click','#searchbar_sp',function () {
                // console.log(this);
                global.location.href = '/search-view'
            });
            document.querySelector('body > a').hidden = true;
        },
        initSsyPage: function({tbCode}){
            const copyModal = $('#copy-modal');
            const copyWrapDom = $('#copyWrap');
            $(global.document).on('click','#close-modal-btn',function () {
                copyText(copyWrapDom);
                const className = copyModal.attr('class');
                const isClosed = /modal-show/.exec(className);
                const targetClassName = isClosed?className.replace(/modal-show/,'modal-close'):className;
                !(className === targetClassName) && copyModal.attr('class',targetClassName);
            });
            $(global.document).on('click','#cat',function () {
                const className = copyModal.attr('class');
                const text = [
                    '天猫全球狂欢节开始啦!',
                    '亿元红包提前抢，最高1111元！',
                    '红包抢得好，双11没烦恼！',
                    '立即复制这条信息',
                    tbCode,
                    ',打开淘宝即可领取红包.'
                ].join('');
                copyWrapDom.val(text);
                const isClosed = /modal-close/.exec(className);
                const targetClassName = isClosed?className.replace(/modal-close/,'modal-show'):className;
                !(className === targetClassName) && copyModal.attr('class',targetClassName);
            });
        },
        initInvite: function(){
            $(global.document).on('click','#catMateriel',function () {
                global.location.href = '/mine/invitation/materiel'
            })
        },
        initRegister:function(){
            const self = this;
            const numberInput = $('#input-number');
            $('#register-form').submit(function () {
                const params = $(this).serializeArray();
                const number = params[0].value;
                const captcha = params[1].value;
                const password = params[2].value;
                // const code = params[3].value;
                // let inviteCode = self.findUrlParam('inviteCode');
                // if (!inviteCode) {
                //     inviteCode = code;
                // }
                if (!matchPhoneNumber(number)){
                    alert('请输入正确的手机号码');
                    return false;
                }else if(!(/^\d{6}$/.test(captcha))){
                    alert('请输入正确的验证码');
                    return false;
                }else if(password.length === 0){
                    alert('请输入正确的密码');
                    return false;
                }
                //else if(inviteCode.length!==6){
                    // alert('请输入正确的邀请码');
                    // return false;
                // }
                (function (req) {
                    $.post('/register',req,function (resp) {
                        console.log(resp);
                        if (resp.code === 0){
                            alert('注册成功');
                            global.location.href = '/login'
                        } else {
                            alert(resp.msg);
                        }
                    });
                })({
                    number:number,
                    captcha:captcha,
                    password:md5(password),
                    // inviteCode:inviteCode
                });
                return false;
            });
            $(global.document).on('click','#btn-getCaptcha',function () {
                const number = numberInput.val();
                if(!matchPhoneNumber(number)){
                    alert("请输入正确的手机号码");
                    return;
                }
                $('#btn-getCaptcha').css("pointer-events", "none");
                const params = {number:number,type:1};
                $.post('/api/sms/captcha',params,function (resp) {
                    const {code,msg,data} = resp;
                    if (code === 0) {
                        self.times('#btn-getCaptcha');
                    }else{
                        $('#btn-getCaptcha').css("pointer-events", "auto");
                        alert(msg);
                    }
                })
            })
        },
        initBindPhone:function(){
            const phoneInput = $("input[name='phone']");
            const captchaInput = $("input[name='captcha']");
            const self = this;
            $(global.document).on('click','#btn_get-vcode',function () {
                const number = phoneInput.val();
                if (!matchPhoneNumber(number)){
                    // alert('请输入正确的手机号码');
                    weui.alert('请输入正确的手机号码');
                    return;
                }
                const params = {number:number};
                $.post('/api/sms/captcha',params,function (resp) {
                    const {code,msg,data} = resp;
                    if (code === 0) {
                        self.times('#btn_get-vcode');
                    }else{
                        $('#btn_get-vcode').css("pointer-events", "auto");
                        weui.alert(msg);
                    }
                });
            });
            $(global.document).on('click','#btn_bind',function () {
                const phone = phoneInput.val();
                const captcha = captchaInput.val();
                if (!(/^\d{6}$/.test(captcha))){
                    weui.alert('请输入有效的验证码');
                    return;
                }
                const params = {phone:phone,captcha:captcha};
                $.post('/api/user/bind_phone',params,function (resp) {
                    const {code,msg,data} = resp;
                    if (code === 0) {
                        window.location.replace('/mine/bind_phone/success');
                    }else if (code === -1) {
                        weui.alert(msg);
                    }else if(code === -2){
                        weui.alert(msg);
                    }
                });
            });
        },
        initRegisterV2:function(){
            const self = this;
            const inviteCode = this.findUrlParam('inviteCode');
            const numberInput = $('#input-number');
            const tipLabel = $('.reg_v2_tip');
            tipLabel.hide();
            $(global.document).on('focus','input',function () {
                tipLabel.text('');
                tipLabel.hide();
            });
            $('#register-form').submit(function () {
                const params = $(this).serializeArray();
                const number = params[0].value;
                const captcha = params[1].value;
                const password = params[2].value;
                if (!matchPhoneNumber(number)){
                    tipLabel.text('请输入正确的手机号码!!');
                    tipLabel.show();
                    return false;
                }else if(!(/^\d{6}$/.test(captcha))){
                    tipLabel.text('请输入正确的验证码!!');
                    tipLabel.show();
                    return false;
                }else if(password.length === 0){
                    tipLabel.text('请输入密码!!');
                    tipLabel.show();
                    return false;
                }
                (function (req) {
                    $.post('/register',req,function (resp) {
                        const {code,msg,data} = resp;
                        if (code === 0){
                            tipLabel.text('注册成功');
                            tipLabel.show();
                            global.location.href = '/guide'
                        } else {
                            tipLabel.text(msg);
                            tipLabel.show();
                        }
                    })
                })({
                    number:number,
                    captcha:captcha,
                    password:md5(password),
                    inviteCode:inviteCode
                });
                return false;
            });
            $(global.document).on('click','#btn-getCaptcha',function () {
                const number = numberInput.val();
                if(!matchPhoneNumber(number)){
                    tipLabel.text('请输入正确的手机号码!!');
                    tipLabel.show();
                    return;
                }
                $('#btn-getCaptcha').css("pointer-events", "none");
                const params = {number:number,type:1};
                $.post('/api/sms/captcha',params,function (resp) {
                    const {code,msg,data} = resp;
                    if (code === 0) {
                        self.times('#btn-getCaptcha');
                    }else{
                        $('#btn-getCaptcha').css("pointer-events", "auto");
                        tipLabel.text(msg);
                        tipLabel.show();
                    }
                })
            })

        },
        times:function(selector){
            const self = this;
            if(self.keepTime === 0){
                $(selector).text("获取验证码");
                $(selector).css("pointer-events", "auto");
                self.keepTime = 60;
            }else{
                $(selector).text('重新发送('+self.keepTime+'s)');
                $(selector).css("pointer-events", "none");
                self.keepTime--;
                setTimeout(function () {
                    self.times(selector);
                },1000);
            }
        },
        initMineSettings:function({userInfo}){
            const self = this;
            const {phoneNumber} = userInfo;
            $(global.document).on('click','#cell_bindPhone',function () {
                if (phoneNumber) {
                    // weui.alert('暂无法修改绑定手机号码');
                    window.location.href = '/mine/bind_phone';
                    return;
                }
                window.location.href = '/mine/bind_phone'
            });
            $(global.document).on('click','#btn-quit',function(){
                // delCookie('token');
                global.location.href = '/logout'
            });
        },
        initSubsidiary:function(){
            const self = this;
            let pageNo = 1;
            let lastPage = false;
            $.get('/api/user/subsidiary',{pageNo:pageNo},function (resp) {
                const {code,data,msg} = resp;
                if (code === 0) {
                    let html = '';
                    if (data.length>0) {
                        data.forEach(function ({username,userAvatar,phoneNumber,time,timeString}) {
                            html += self.loadHtmlTemplate('#list-item', {
                                userAvatar:userAvatar?userAvatar:'/static/img/img-avatar-1.png',
                                username:username==null?'暂无昵称':username,
                                phoneNumber:phoneNumber==null?'暂未绑定手机号码':phoneNumber,
                                time:timeString});
                        });
                    }else{
                        html = self.loadHtmlTemplate('#list-placeholder-temp')
                    }
                    $('#record-list').append(html);
                }
            });
            $(global).scroll(this.handleScrollEvent(function () {
                if (lastPage) {
                    return;
                }
                $.get('/api/user/subsidiary',{pageNo:++pageNo},function (resp) {
                    const {code,data,msg} = resp;
                    if (code === 0) {
                        let html = '';
                        data.forEach(function ({username,phoneNumber,time}) {
                            html += self.loadHtmlTemplate('#list-item', {
                                username:username==null?'暂无昵称':username,
                                phoneNumber:phoneNumber,
                                time:function () {
                                    return new Date(time).format('yyyy-MM-dd');
                                }()});
                        });
                        $('#record-list').append(html);
                        if (data.length < 10) {
                            pageNo--;
                            lastPage = true;
                        }
                    }else{
                        pageNo--;
                        lastPage = true;
                    }
                    self.resetLoading();
                });
            }));
        },
        initProfitList:function(){
            const handlerProfitListViewCreate = function () {
                this.showPlaceholder();
            };
            new ListView('#profitList',{
                onCreate:handlerProfitListViewCreate
            })
        },
        initBalance:function(){
            // console.log(window.history.replaceState(null,'','http://'));

            // const tipModal = $('#tip-modal');
            // $(global.document).on('click','#tip-modal-btn',function () {
            //     window.location.href = '/mine/balance/draw_cash';
            //     // const className = tipModal.attr('class');
            //     // const isClosed = /modal-show/.exec(className);
            //     // const targetClassName = isClosed?className.replace(/modal-show/,'modal-close'):className;
            //     // !(className === targetClassName) && tipModal.attr('class',targetClassName);
            // });
            $(global.document).on('click','#draw-cash-btn',function () {
                // window.location.replace('/mine/balance/draw_cash');
                window.location.href = '/mine/balance/draw_cash';
                // const className = tipModal.attr('class');
                // const isClosed = /modal-close/.exec(className);
                // const targetClassName = isClosed?className.replace(/modal-close/,'modal-show'):className;
                // !(className === targetClassName) && tipModal.attr('class',targetClassName);
            });
            const self = this;
            let pageNo = 1;
            let lastPage = false;
            // $.post('/api/user/trading/list',{pageNo:pageNo},function (resp) {
            //     const {code,data,msg} = resp;
            //     if (code === 0) {
            //         let html = '';
            //         data.forEach(function ({type,time,typeString,amount}) {
            //             const typeFlg = (type===1)?'+':'-';
            //             const typeColor = (type===1)?'#34a853':'#eb4c3e';
            //             html += self.loadHtmlTemplate('#list-item',
            //                 {type:typeString, time:time,typeFlg:typeFlg,amount:amount.formats(),typeColor:typeColor});
            //         });
            //         $('#record-list').append(html);
            //     }
            // });
            // $(global).scroll(this.handleScrollEvent(function () {
            //     if (lastPage) {
            //         return;
            //     }
            //     $.post('/api/user/trading/list',{pageNo:++pageNo},function (resp) {
            //         const {code,data,msg} = resp;
            //         if (code === 0) {
            //             let html = '';
            //             data.forEach(function ({type,time,typeString,amount}) {
            //                 const typeFlg = (type===1)?'+':'-';
            //                 const typeColor = (type===1)?'#34a853':'#eb4c3e';
            //                 html += self.loadHtmlTemplate('#list-item',
            //                     {type:typeString, time:time,typeFlg:typeFlg,amount:amount.formats(),typeColor:typeColor});
            //             });
            //             $('#record-list').append(html);
            //             if (data.length < 10) {
            //                 pageNo--;
            //                 lastPage = true;
            //             }
            //         }else{
            //             pageNo--;
            //             lastPage = true;
            //         }
            //         self.resetLoading();
            //     });
            // }));
        },
        loadHtmlTemplate:function(tId,arg){
            let s = $(tId).html();
            if (arg === null || typeof arg === typeof undefined) {
                return s;
            }
            Object.keys(arg).forEach(function (k) {
                const reg = new RegExp('%{'+k+'}%');
                const v = arg[k];
                s = s.replace(reg,v);
            });
            return s;
        },
        initProfit:function(){

        },
        initMineOrder: function({token}){
            const handlerOrderListViewCreate = function () {
                let access_token = token;
                if (!token) {
                    access_token = null;
                }
                GETList('/api/order/list',1,{access_token:access_token}).then(function (data) {
                    if(data == null||data.length === 0){
                        this.showPlaceholder();
                        return;
                    }
                    this.load(data);
                }.bind(this));
            };
            const handelListViewRender = function(item){
                const {pictUrl} = item;
                let pictUrlReal = '/static/img/img_item_none.png';
                if (pictUrl) {
                    pictUrlReal = pictUrl;
                }
                const args = Object.assign(item, {
                    pictUrl:pictUrlReal
                });
                return this.render4Tmpl('#tmpl-orderItem',args);
            };
            const handlerOrderListViewLoadMore = function (pageNo) {
                GETList('/api/order/list',pageNo,{}).then(function (data) {
                    if(data == null||data.length === 0){
                        this.loadingEmpty();
                        return;
                    }
                    this.load(data,function () {
                        this.unlockLoading();
                    });
                }.bind(this));
            };
            new ListView('#orderList',{
                onCreate:handlerOrderListViewCreate,
                onLoadMore:handlerOrderListViewLoadMore,
                render:handelListViewRender
            })
        },
        initShare: function(data){
            const {title,hasCoupon,price,finalPrice,shortLinkUrl,tbCode} = data.goodsInfo;
            const finalPriceText = hasCoupon?'券后价':'折扣价';
            const defaultShareText = title + '\n' +
                '【原价】￥' + price + '\n'+
                '【'+finalPriceText+'】￥' + finalPrice + '\n' +
                '【下单链接】{%选择分享渠道后自动生成链接%}' + '\n'+
                '===============\n'+
                '复制这条消息，{%选择分享渠道后自动生成淘口令%}，'+
                '打开【手机淘宝】即可查看';
            const shareEditor = $('.share-editor');
            shareEditor.val(defaultShareText);
            $(global.document).on('click','.copy',function () {
                const text = shareEditor.val();
                let target = text.replace(/{%选择分享渠道后自动生成链接%}/,shortLinkUrl);
                target = target.replace(/{%选择分享渠道后自动生成淘口令%}/,tbCode);
                shareEditor.val(target);
                shareEditor[0].setSelectionRange(0,target.length);
                global.document.execCommand('copy');
                shareEditor.val(text);
                shareEditor[0].blur();
                alert('已经成功复制到剪贴板中!');
            });
            $(window.document).on('click','#catMateriel',function () {
                const numId = getUrlParam('numId');
                window.location.href = '/goods/share/materiel?numId=' + numId;
            });
        },
        initSearch: function(){
            const searchBar = $('#searchbar');
            const searchBarForm = $('#searchbar_form');
            searchBar.on('click', function() {
                $(this).focus();
            });
            searchBar.trigger('click');
            searchBarForm.submit(function () {
                const params = $(this).serializeArray();
                if (params[0].value.length === 0) {
                    alert('请输入搜索关键词');
                    return false;
                }
                return true;
            });
        },
        getSortFields: function(){
            return [{
                key:'default',
                title:'推荐'
            },{
                key:'coupon',
                title:'优惠券'
            },{
                key:'volume',
                title:'销量',
                multiple:true
            },{
                key:'price',
                title:'价格',
                multiple:true
            }];
        },

        initSearchResult: function({access_token}){
            window.access_token = access_token;
            const keyword = getUrlParam('q');
            const keywordDecodeVal = keyword.replace(/\+/g,' ').replace(/%2B/g,'+');
            const searchBar = $('#searchbar');
            searchBar.val(keywordDecodeVal);
            const searchBarForm = $('#searchbar_form');
            searchBarForm.submit(function () {
                const params = $(this).serializeArray();
                if (params[0].value.length === 0) {
                    alert('请输入搜索关键词');
                    return false;
                }
                return true;
            });
            new ListView('#result-list',{
                sortDefaultKey:'default',
                sortRender:'.group-filter',
                sortData: this.getSortFields(),
                onSortChange:this.handleListViewSortChange,
                onCreate:this.handleSearchResultListViewCreate,
                onLoadMore:this.handleListViewLoadMore,
                render:this.handelListViewRender
            });
        },
        handleGroupListViewCreate: function(){
            const pathName = global.location.pathname;
            const categoryRegexp = /\/category\/(\d+)/.exec(pathName);
            const groupRegexp = /\/group\/(\d+)(\?|$)/.exec(pathName);
            let access_token = window.access_token;
            if (!access_token) {
                access_token = null;
            }
            if (categoryRegexp!==null){
                const cId = categoryRegexp[1];
                this.state = {cId:cId,apiUrl:('/api/category/' + cId),access_token:access_token};

            }else if(groupRegexp !== null){
                const gId = groupRegexp[1];
                const tag = getUrlParam('tag');
                this.state = {gId:gId,apiUrl:('/api/group/' + gId),tag:tag,access_token:access_token};
            }
            const {apiUrl} = this.state;
            if (!apiUrl) {
                return;
            }
            GETList(apiUrl,1,state2requestArgs.bind(this)()).then(function (data) {
                if(data == null||data.length === 0){
                    this.showPlaceholder();
                    return;
                }
                this.load(data);
            }.bind(this))
        },
        handleSearchResultListViewCreate:function(){
            const keyword = getUrlParam('q');
            const keywordDecodeVal = keyword.replace(/\+/g,' ').replace(/%2B/g,'+');
            let access_token = window.access_token;
            if (!access_token) {
                access_token = null;
            }
            this.state = {apiUrl:'/api/search',q:keywordDecodeVal,access_token:access_token};
            const {apiUrl} = this.state;
            GETList(apiUrl,1,state2requestArgs.bind(this)()).then(function (data) {
                if(data == null||data.length === 0){
                    this.showPlaceholder();
                    return;
                }
                this.load(data);
            }.bind(this))
        },
        handleListViewLoadMore:function(pageNo){
            const {apiUrl} = this.state;
            GETList(apiUrl,pageNo,state2requestArgs.bind(this)()).then(function (data) {
                if(data == null||data.length === 0){
                    this.loadingEmpty();
                    return;
                }
                this.load(data,function () {
                    this.unlockLoading();
                });
            }.bind(this));
        },
        handleListViewSortChange:function(s){
            const {apiUrl} = this.state;
            const {key,state} = s;
            let args = {};
            if (key !== 'default'&&key !== 'coupon') {
                args = {sort:(key + '!' + (!state?'desc':state))};
                this.setState({sort:args.sort,hasCoupon:null});
            }else if (key === 'coupon'){
                args = {has_coupon:'true'};
                this.setState({hasCoupon:args.has_coupon,sort:null});
            }else{
                this.setState({hasCoupon:null,sort:null});
            }
            GETList(apiUrl,this.pageNo,state2requestArgs.bind(this)()).then(function (data) {
                if(data == null||data.length === 0){
                    this.showPlaceholder();
                    return;
                }
                this.load(data,null,true);
            }.bind(this));
        },
        handelListViewRender:function(item){
            const {hasCoupon,oldPrice,finalPrice,couponMoney,commissionMoney} = item;
            let couponDom = '';
            if (couponMoney) {
                if (couponMoney > 99){
                    couponDom = [
                        '<div class="coupon">',
                        '<span style="font-size: 10px;">',
                        couponMoney,
                        '￥</span>',
                        '</div>'
                    ].join('');
                } else{
                    couponDom = [
                        '<div class="coupon">',
                        '<span>',
                        couponMoney,
                        '￥</span>',
                        '</div>'
                    ].join('');
                }
            }
            let commissionDom = '';
            if (commissionMoney){
                commissionDom = [
                    '<div class="goods-extra2 clearfix">',
                    '<span class="real-price commissionMoney">',
                    '预估收益:￥',commissionMoney,
                    '</span>',
                    '</div>'
                ].join('');
            }
            const priceText = hasCoupon?'券后价':'折后价';
            const args = Object.assign(item, {
                priceText: priceText,
                oldPrice: oldPrice.formats(),
                finalPrice: finalPrice.formats(),
                couponDom: couponDom,
                commissionDom:commissionDom
            },{});
            return this.render4Tmpl('#tmpl-goodsItem',args);
        },
        initGroup: function ({access_token}){
            window.access_token = access_token;
            new ListView('#group-list',{
                sortDefaultKey:'default',
                sortRender:'.group-filter',
                sortData: this.getSortFields(),
                onSortChange:this.handleListViewSortChange,
                onCreate:this.handleGroupListViewCreate,
                onLoadMore:this.handleListViewLoadMore,
                render:this.handelListViewRender
            });
        },
        findUrlParam: function(param){
            const reg = RegExp('(^|&)'+ param +'=([^&]*)(&|$)');
            const s = global.location.search.substr(1).match(reg);
            if (s != null){
                return decodeURI(s[2]);
            }
            return null;
        },
        initGoods: function(){
            // 初始化轮播图
            $('.slider-wrapper').slick({
                autoplay: true,
                autoplaySpeed: 2500,
                dots: true,
                arrows: false
            });
            const showLoading = function () {
                $('body').loading({
                    loadingWidth:120,
                    title:'',
                    name:'loading',
                    discription:'',
                    direction:'column',
                    type:'origin',
                    // originBg:'#71EA71',
                    originDivWidth:40,
                    originDivHeight:40,
                    originWidth:6,
                    originHeight:6,
                    smallLoading:false,
                    loadingMaskBg:'rgba(0,0,0,0.2)'
                });
            };
            const copyModal = $('#copy-modal');
            const copyWrapDom = $('#copyWrap');
            $(global.document).on('click','#close-modal-btn',function () {
                copyText(copyWrapDom);
                const className = copyModal.attr('class');
                const isClosed = /modal-show/.exec(className);
                const targetClassName = isClosed?className.replace(/modal-show/,'modal-close'):className;
                !(className === targetClassName) && copyModal.attr('class',targetClassName);
            });
            $(global.document).on('click','#tools-share',function () {
                const token = getCookie('token');
                if (token) {
                    const goodsNumId = $(this).attr('goods-numId');
                    global.location.href = '/goods/share?numId=' + goodsNumId;
                }else{
                    global.location.href = '/login';
                }
            });
            $(global.document).on('click','#tools-buy',function () {
                const token = getCookie('token');
                if (!token) {
                    global.location.href = '/login';
                    return;
                }
                const className = copyModal.attr('class');
                const numId = $(this).attr('goods-numId');
                !function (call) {
                    const url = '/api/goods/buy?numId=' + numId;
                    showLoading();
                    $.get(url,function (resp) {
                        call(resp);
                    });
                }(function (resp) {
                    removeLoading('loading');
                    if (resp.code === 0) {
                        const text = resp.data;
                        copyWrapDom.val(text);
                        const isClosed = /modal-close/.exec(className);
                        const targetClassName = isClosed?className.replace(/modal-close/,'modal-show'):className;
                        !(className === targetClassName) && copyModal.attr('class',targetClassName);
                    }else if (resp.code === -2){
                        window.location.href = '/login';
                    }
                });
            });
        },
        initGoodsV2: function(){
            // 初始化轮播图
            $('.slider-wrapper').slick({
                autoplay: true,
                autoplaySpeed: 2500,
                dots: true,
                arrows: false
            });
            const showLoading = function () {
                $('body').loading({
                    loadingWidth:120,
                    title:'',
                    name:'loading',
                    discription:'',
                    direction:'column',
                    type:'origin',
                    // originBg:'#71EA71',
                    originDivWidth:40,
                    originDivHeight:40,
                    originWidth:6,
                    originHeight:6,
                    smallLoading:false,
                    loadingMaskBg:'rgba(0,0,0,0.2)'
                });
            };
            const copyModal = $('#copy-modal');
            const copyWrapDom = $('#copyWrap');
            $(global.document).on('click','#close-modal-btn',function () {
                copyText(copyWrapDom);
                const className = copyModal.attr('class');
                const isClosed = /modal-show/.exec(className);
                const targetClassName = isClosed?className.replace(/modal-show/,'modal-close'):className;
                !(className === targetClassName) && copyModal.attr('class',targetClassName);
            });
            $(global.document).on('click','#tools-buy',function () {
                const className = copyModal.attr('class');
                const numId = $(this).attr('goods-numId');
                let uCode = getUrlParam('u_code');
                if (!uCode) {
                    uCode='none';
                }
                !function (call) {
                    const url = '/api/goods/buy_v2?numId=' + numId + '&u_code=' + uCode;
                    showLoading();
                    $.get(url,function (resp) {
                        call(resp);
                    });
                }(function (resp) {
                    removeLoading('loading');
                    if (resp.code === 0) {
                        const text = resp.data;
                        copyWrapDom.val(text);
                        const isClosed = /modal-close/.exec(className);
                        const targetClassName = isClosed?className.replace(/modal-close/,'modal-show'):className;
                        !(className === targetClassName) && copyModal.attr('class',targetClassName);
                    }else if (resp.code === -2){
                        window.location.href = '/login';
                    }
                });
            });
        },
        initLogin: function(){
            $('#login-form').submit(function () {
                const params = $(this).serializeArray();
                const number = params[0].value;
                const password = params[1].value;
                if (!matchPhoneNumber(number)){
                    alert('请输入正确的手机号码');
                    return false;
                }else if(password.length === 0){
                    alert('请输入正确的登录密码');
                    return false;
                }
                (function (req) {
                    $.post('/login',req,function (resp) {
                        if (resp.code === 0){
                            global.location.href = '/mine'
                        } else {
                            alert(resp.msg);
                        }
                    })
                })({
                    phoneNumber:number,
                    password:md5(password)
                });
                return false;
            });
        },
        getAccessToken: function(){
            return global.localStorage.getItem('access_token');
        },
        getRereshToken: function(){
            return global.localStorage.getItem('refresh_token');
        },
        initAuthLogin: function(){
            const self = this;
            $('#login-form').submit(function () {
                const params = $(this).serializeArray();
                if (params[0].value.length === 0){
                    alert('请输入正确的手机号码');
                    return false;
                }else if(params[1].value.length === 0){
                    alert('请输入正确的登录密码');
                    return false;
                }
                (function (req) {
                    $.post('/api/auth/login',req,function (resp) {
                        if (resp.code === 0){
                            const {redirect_uri,code,state} = resp.data;
                            global.location.href = redirect_uri;
                        } else {
                            alert(resp.msg);
                        }
                    })
                })({
                    phoneNumber:params[0].value,
                    password:md5(params[1].value),
                    redirect_uri : self.findUrlParam('redirect_uri'),
                    state: self.findUrlParam('state'),
                    response_type: self.findUrlParam('response_type')
                });
                return false;
            });
        },
        initIndex: function () {
            // 初始化轮播图
            $('.slider-wrapper').slick({
                autoplay: true,
                autoplaySpeed: 2500,
                dots: true,
                arrows: false
            });
            let pageNo = 1;
            const self = this;
            $(global.document).on('click','.item-activity',function () {
                const id = $(this).attr('id');
                if (id === 'sub-9k9') {
                    global.location.href = '/group/5?tag=9k9';
                }else if(id === 'sub-czbp'){
                    global.location.href = '/group/7';
                }else if(id === 'sub-jhs'){
                    global.location.href = '/group/8';
                }else if(id === 'sub-djtm'){
                    global.location.href = '/group/9';
                }
            });
            $(global.document).on('click','#home-ad1',function () {
                window.location.href = '/page/0'
            });
            // 底部加载更多
            $(global).scroll(this.handleScrollEvent(function () {
                $.get('/hotNews',{page_no:++pageNo},function (resp) {
                    if (resp.code === -1){
                        pageNo -= 1
                    }
                    if (!resp.data || resp.data.length===0){
                        pageNo -= 1
                    }
                    let data = resp.data;
                    let allTemp = '';
                    for (let i=0;i<data.length;i++){
                        allTemp += function (item) {
                            const {
                                goodsNumId, goodsPictUrl, goodsTitle,
                                oldPrice, volume, finalPrice,
                                hasCoupon,couponMoney,commissionMoney
                            } = item;
                            const priceText = hasCoupon?'券后价':'折扣价';
                            let couponFlag = '';

                            if (couponMoney > 99){
                                couponFlag = [
                                    '<div class="coupon">',
                                    '<span style="font-size: 10px;">',
                                    couponMoney,
                                    '￥</span>',
                                    '</div>'
                                ].join('');
                            } else{
                                couponFlag = [
                                    '<div class="coupon">',
                                    '<span>',
                                    couponMoney,
                                    '￥</span>',
                                    '</div>'
                                ].join('');
                            }
                            let commissionDom = '';
                            if (commissionMoney){
                                commissionDom = [
                                    '<div class="goods-extra2 clearfix">',
                                        '<span class="real-price commissionMoney">',
                                        '预估收益:￥',commissionMoney,
                                        '</span>',
                                    '</div>'
                                ].join('');
                            }
                            return '<li id="'+goodsNumId+'" class="goods-list-item"><div class="goods-item">\
                                <img class="goods-img" src="'+goodsPictUrl+'" alt="商品">\
                                <div class="goods-title">'+goodsTitle+'</div>'+commissionDom+' \
                                <div class="goods-extra1 clearfix">\
                                <del class="old-price">原价:￥'+parseDouble(oldPrice)+'</del>\
                                <span class="sales-num">月销量:'+volume+'</span>\
                                </div><div class="goods-extra2 clearfix">\
                                <span class="real-price">'+priceText+':￥'+parseDouble(finalPrice)+'</span>'+couponFlag+'  \
                                </div></div></li>';
                        }(data[i]);
                    }
                    $("#new-goods").append(allTemp);
                    self.resetLoading();
                })
            }))
        },
        initMine: function(){
            const self = this;
            $(global.document).on('click','.mine-user-info',function () {
                const isLogin = getCookie('token');
                if (isLogin){
                }else {
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#client-setting',function(){
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/setting';
                }else{
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#user-balance',function () {
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/balance';
                }else{
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#user-profit',function () {
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/profit';
                }else{
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#user-pending',function () {
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/profit';
                }else{
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#mine-orders',function () {
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/orders';
                }else{
                    window.location.href = '/login';
                }
            });
            $(global.document).on('click','#mine-invite',function () {
                const isLogin = getCookie('token');
                if (isLogin) {
                    window.location.href = '/mine/invitation';
                }else{
                    window.location.href = '/login';
                }
            });
        },
        initDraw: function({balance}){
            const self = this;
            self.drawType = 1;
            const drawTypeLabel = $('#label_draw-type');
            const balanceLabel = $('#label_balance');
            const moneyInput = $("input[name='money']");
            balanceLabel.text(`￥${balance.formats()}`);
            $(window.document).on('click','#row_draw-type',function () {
                weui.actionSheet(
                    [
                        {
                            label: '微信零钱',
                            onClick: function () {
                                self.drawType = 1;
                                drawTypeLabel.text('微信零钱');
                            }
                        }
                    // {
                    //     label: '支付宝余额',
                    //     onClick: function () {
                    //         self.drawType = 1;
                    //         drawTypeLabel.text('支付宝余额');
                    //     }
                    // }
                    ], [{
                            label: '取消',
                            onClick: function () {

                            }
                        }]
                );
            });
            $(window.document).on('click','#btn_draw-cash',function () {
                console.log('到账类型:',self.drawType);
                const moneyText = moneyInput.val();
                const money = parseFloat(moneyText);
                if (!money) {
                    weui.alert('请输入有效的金额');
                    return;
                }
                if (money < 10) {
                    weui.alert('提现金额最少10元起');
                    return;
                }
                if (money>balance){
                    weui.alert('提现金额超过可用余额');
                    return;
                }
                if (!/^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/.test(moneyText)){
                    weui.alert('金额最大保留两位小数');
                    return;
                }
                const req = {pay_way:self.drawType,money:money};
                $.post('/api/user/balance/draw_cash',req,function (resp) {
                    const {code,data,msg} = resp;
                    if (code === 0){
                        window.location.replace('/mine/balance/draw_cash/success');
                    } else if(code === -2){
                        weui.confirm('绑定手机号码后才可以提现哦', {
                            buttons: [{
                                label: '取消',
                                type: 'default',
                                onClick: function(){ console.log('no') }
                            }, {
                                label: '去绑定',
                                type: 'primary',
                                onClick: function(){ window.location.href='/mine/bind_phone' }
                            }]
                        });
                    }else{
                        weui.alert(msg);
                    }
                });

                // if (!/a/.test(money)){
                //     weui.alert('alert');
                //     return;
                // }
                //
            });
            $(window.document).on('click','#label_draw-all',function () {
                // balanceLabel.text(`￥${balance}`);
                // console.log('到账类型:',self.drawType);

                moneyInput.val(`${balance}`);
            })

        },
        initCategory: function(data){
            const categoryTree = data.categoryTree;
            const categoryRootsDom = (function () {
                let dom = '';
                for (let i=0;i<categoryTree.length;i++) {
                    const item = categoryTree[i];
                    dom+='<li id="cid='+item.id+'" class="list-item"><a href="#cid='+item.id+'">'+
                        item.name +
                        '</a></li>'
                }
                return dom;
            })();
            const findChildDom = (function () {
                return function (id) {
                    for (let i=0;i<categoryTree.length;i++) {
                        const item = categoryTree[i];
                        if (item.id === id){
                            return (function () {
                                if (item.children == null){
                                    return null;
                                }
                                const children = item.children;
                                let dom = '';
                                for (let i=0;i<children.length;i++) {
                                    const childrenItem = children[i];
                                    let imageUrl = childrenItem.imgUrl;
                                    if (imageUrl == null || imageUrl.length === 0){
                                        imageUrl = '/static/img/img_good1.jpg'
                                    }
                                    dom +='<li style="cursor: pointer" id="category-'+childrenItem.id+'" class="list-item child-item">' +
                                        '<div class="category-sec-item">'+
                                        '<img class="item-img" src="'+imageUrl+'">'+
                                        '<div class="item-title">'+childrenItem.name+'</div></div></li>';
                                }
                                return dom;
                            })();
                        }
                    }
                    return null;
                }
            })();
            global.addEventListener('hashchange',function (ev) {
                const hash = global.location.hash;
                const cid = parseInt(/#cid=(\d+)/.exec(hash)[1]);
                const targetDom = '<ul id="secList" class="list-sec">'+
                    findChildDom(cid) + '</ul>';
                $("#secList").replaceWith(targetDom);
                const selector = '#item-cid-' + cid;
                $('.list-root .active').removeClass('active');
            });
            $(global.document).on('click','.child-item',function () {
                const attrId = $(this).attr('id');
                const id = /^category-(\d+$)/.exec(attrId)[1];
                global.location.href = '/category/' + id;
            });
            if (categoryTree !=null && categoryTree.length > 0){
                $('.list-root').append(categoryRootsDom);
                const firstId = categoryTree[0].id;
                const firstDom = findChildDom(firstId);
                $('#secList').append(firstDom);
                const selector = '#cid\\=' + firstId;
                $(selector).addClass('active');
            }
        },
        handleScrollEvent: function (loadMore) {
            const self = this;
            return function () {
                const t = $(global).scrollTop();
                const h = $(window).height();
                const dh = $(document).height();
                if (t + h > dh - 20 && !self.loading) {
                    self.loading = true;
                    loadMore();
                }
            };
        },
        resetLoading: function () {
            this.loading = false;
        },
        lockLoading: function () {
            this.loading = true;
        }
    };
    function parseDouble(n) {
        return Math.floor(n*100) / 100;
    }
    function matchPhoneNumber(number) {
        return /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147)|(171))\d{8}$/.test(number);
    }
    function copyText(selector) {
        const sd = $(selector);
        const dom = sd[0];
        const text = sd.val();
        dom.focus();
        dom.select();
        dom.setSelectionRange(0,text.length);
        global.document.execCommand('copy');
        dom.blur();
    }
    function getCookie(name) {
        let arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return decodeURI(arr[2]);
        else
            return null;
    }
    function delCookie(key) {
        const date = new Date();
        date.setTime(date.getTime() -1);
        global.document.cookie = key + '=; expires=' + date.toUTCString() + '; path=/';
    }
    const GET = function(url){
        return fetch(url).then(function (resp) {
            return resp.json();
        }).then(function (resp) {
            const {code,data,msg} = resp;
            return new Promise(function (resolve, reject) {
                if (code === 0) {
                    resolve(data);
                }else{
                    reject(new Error(msg));
                }
            });
        })
    };
    const GETList = function(url,pageNo,attr){
        let param = {'page_no':pageNo};
        if (!$.isEmptyObject(attr)){
            param = Object.assign(param,attr);
        }
        const paramStr = $.param(param);
        const requestUrl = url +'?' +paramStr;

        // console.log('requestUrl:',requestUrl);
        return GET(requestUrl);
    };
    const getUrlParam = function(param){
        const reg = RegExp('(^|&)'+ param +'=([^&]*)(&|$)');
        const s = global.location.search.substr(1).match(reg);
        if (s != null){
            return decodeURI(s[2]);
        }
        return null;
    };
    const urlParamsSerialize = function (obj) {
        return $.param(obj);
    };
    const state2requestArgs = function(){
        const {sort,hasCoupon,tag,q,access_token} = this.state;
        let args = {};
        if (sort) {
            args = Object.assign(args,
                {sort: sort});
        }
        if (hasCoupon) {
            args = Object.assign(args,
                {has_coupon: hasCoupon});
        }
        if (tag) {
            args = Object.assign(args,
                {tag: tag});
        }
        if(q){
            args = Object.assign(args,
                {q: q});
        }
        if(access_token&&access_token!==''){
            args = Object.assign(args,
                {access_token: access_token});
        }
        return args;
    };
    !('S7BuyClient' in global) && (global.S7BuyClient = S7BuyClient);
}(window, jQuery);